home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / ast_text / faqs / perl-fqs / part2 < prev   
Encoding:
Internet Message Format  |  1993-06-28  |  46.4 KB

  1. Path: senator-bedfellow.mit.edu!enterpoop.mit.edu!news.media.mit.edu!uhog.mit.edu!eddie.mit.edu!europa.eng.gtefsd.com!howland.reston.ans.net!gatech!asuvax!chnews!ornews.intel.com!news
  2. From: Randal L. Schwartz <merlyn@ora.com>
  3. Newsgroups: comp.lang.perl,news.answers,comp.answers
  4. Subject: comp.lang.perl FAQ (part 2 of 2)
  5. Followup-To: comp.lang.perl
  6. Date: 23 Jun 93 17:49:58 GMT
  7. Organization: Intel Corporation
  8. Lines: 1354
  9. Approved: news-answers-request@MIT.Edu
  10. Message-ID: <merlyn.740857798.6721.3@kandinsky.intel.com>
  11. NNTP-Posting-Host: kandinsky.intel.com
  12. Xref: senator-bedfellow.mit.edu comp.lang.perl:17886 news.answers:9704 comp.answers:1117
  13.  
  14. Archive-name: perl-faq/part2
  15. Version: $Id: perl-tech,v 1.2 92/11/30 05:22:44 tchrist Exp Locker: tchrist $
  16.  
  17. [I have not changed anything here, but I haven't seen Tom post this in
  18. a while.  Maybe I'm going to become the FAQ maintainer... sigh.  For
  19. one thing, this FAQ doesn't address the Llama Book... a glaring
  20. oversight. :-)
  21.  
  22. This version is slightly updated from the one I posted a few days
  23. ago, as pointed out to me by Henk Penning <henkp@cs.ruu.nl>.
  24.  
  25. -- merlyn@ora.com]
  26.  
  27. This posting contains answers to the following techical questions
  28. regarding Perl:
  29.  
  30. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  31. 2.2) Why don't backticks work as they do in shells?  
  32. 2.3) How come Perl operators have different precedence than C operators?
  33. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  34. 2.5) How can I call my system's unique C functions from Perl?
  35. 2.6) Where do I get the include files to do ioctl() or syscall()?
  36. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  37. 2.8) How can I detect keyboard input without reading it?
  38. 2.9) How can I make an array of arrays or other recursive data types?
  39. 2.10) How can I quote a variable to use in a regexp?
  40. 2.11) Why do setuid Perl scripts complain about kernel problems?
  41. 2.12) How do I open a pipe both to and from a command?
  42. 2.13) How can I change the first N letters of a string?
  43. 2.14) How can I manipulate fixed-record-length files?
  44. 2.15) How can I make a file handle local to a subroutine?
  45. 2.16) How can I extract just the unique elements of an array?
  46. 2.17) How can I call alarm() or usleep() from Perl?
  47. 2.18) How can I test whether an array contains a certain element?
  48. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  49. 2.20) Why doesn't Perl interpret my octal data octally?
  50. 2.21) How do I sort an associative array by value instead of by key?
  51. 2.22) How can I capture STDERR from an external command?
  52. 2.23) Why doesn't open return an error when a pipe open fails?
  53. 2.24) How can I compare two date strings?
  54. 2.25) What's the fastest way to code up a given task in perl?
  55. 2.26) How can I know how many entries are in an associative array?
  56. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  57. 2.28) Do I always/never have to quote my strings or use semicolons?
  58. 2.29) How can I translate tildes in a filename?
  59. 2.30) How can I convert my shell script to Perl?
  60. 2.31) What is variable suicide and how can I prevent it?
  61. 2.32) Can I use Perl regular expressions to match balanced text?
  62. 2.33) Can I use Perl to run a telnet or ftp session?
  63. 2.34) What does "Malformed command links" mean?
  64. 2.35) How can I set up a footer format to be used with write()?
  65. 2.36) Why does my Perl program keep growing in size?
  66.  
  67.  
  68. 2.1) What are all these $@*%<> signs and how do I know when to use them?
  69.  
  70.     Those are type specifiers: $ for scalar values, @ for indexed arrays,
  71.     and % for hashed arrays.  The * means all types of that symbol name
  72.     and are sometimes used like pointers; the <> are used for inputting
  73.     a record from a filehandle.  See the question on arrays of arrays
  74.     for more about Perl pointers.
  75.  
  76.     Always make sure to use a $ for single values and @ for multiple ones.
  77.     Thus element 2 of the @foo array is accessed as $foo[2], not @foo[2],
  78.     which is a list of length one (not a scalar), and is a fairly common
  79.     novice mistake.  Sometimes you can get by with @foo[2], but it's
  80.     not really doing what you think it's doing for the reason you think
  81.     it's doing it, which means one of these days, you'll shoot yourself
  82.     in the foot; ponder for a moment what these will really do:
  83.     @foo[0] = `cmd args`;
  84.     @foo[2] = <FILE>;
  85.     Just always say $foo[2] and you'll be happier.
  86.  
  87.     This may seem confusing, but try to think of it this way:  you use the
  88.     character of the type which you *want back*.  You could use @foo[1..3] for
  89.     a slice of three elements of @foo, or even @foo{A,B,C} for a slice of
  90.     of %foo.  This is the same as using ($foo[1], $foo[2], $foo[3]) and
  91.     ($foo{A}, $foo{B}, $foo{C}) respectively.  In fact, you can even use
  92.     lists to subscript arrays and pull out more lists, like @foo[@bar] or
  93.     @foo{@bar}, where @bar is in both cases presumably a list of subscripts.
  94.  
  95.     While there are a few places where you don't actually need these type
  96.     specifiers, except for files, you should always use them.  Note that
  97.     <FILE> is NOT the type specifier for files; it's the equivalent of awk's
  98.     getline function, that is, it reads a line from the handle FILE.  When
  99.     doing open, close, and other operations besides the getline function on
  100.     files, do NOT use the brackets.
  101.  
  102.     Beware of saying:
  103.     $foo = BAR;
  104.     Which wil be interpreted as 
  105.     $foo = 'BAR';
  106.     and not as 
  107.     $foo = <BAR>;
  108.     If you always quote your strings, you'll avoid this trap.
  109.  
  110.     Normally, files are manipulated something like this (with appropriate
  111.     error checking added if it were production code):
  112.  
  113.     open (FILE, ">/tmp/foo.$$");
  114.     print FILE "string\n";
  115.     close FILE;
  116.  
  117.     If instead of a filehandle, you use a normal scalar variable with file
  118.     manipulation functions, this is considered an indirect reference to a
  119.     filehandle.  For example,
  120.  
  121.     $foo = "TEST01";
  122.     open($foo, "file");
  123.  
  124.     After the open, these two while loops are equivalent:
  125.  
  126.     while (<$foo>) {}
  127.     while (<TEST01>) {}
  128.  
  129.     as are these two statements:
  130.     
  131.     close $foo;
  132.     close TEST01;
  133.  
  134.     but NOT to this:
  135.  
  136.     while (<$TEST01>) {} # error
  137.         ^
  138.         ^ note spurious dollar sign
  139.  
  140.     This is another common novice mistake; often it's assumed that
  141.  
  142.     open($foo, "output.$$");
  143.  
  144.     will fill in the value of $foo, which was previously undefined.  
  145.     This just isn't so -- you must set $foo to be the name of a valid
  146.     filehandle before you attempt to open it.
  147.  
  148.  
  149. 2.2) Why don't backticks work as they do in shells?  
  150.  
  151.     Several reason.  One is because backticks do not interpolate within
  152.     double quotes in Perl as they do in shells.  
  153.     
  154.     Let's look at two common mistakes:
  155.  
  156.          $foo = "$bar is `wc $file`";  # WRONG
  157.  
  158.     This should have been:
  159.  
  160.      $foo = "$bar is " . `wc $file`;
  161.  
  162.     But you'll have an extra newline you might not expect.  This
  163.     does not work as expected:
  164.  
  165.       $back = `pwd`; chdir($somewhere); chdir($back); # WRONG
  166.  
  167.     Because backticks do not automatically eat trailing or embedded
  168.     newlines.  The chop() function will remove the last character from
  169.     a string.  This should have been:
  170.  
  171.       chop($back = `pwd`); chdir($somewhere); chdir($back);
  172.  
  173.     You should also be aware that while in the shells, embedding
  174.     single quotes will protect variables, in Perl, you'll need 
  175.     to escape the dollar signs.
  176.  
  177.     Shell: foo=`cmd 'safe $dollar'`
  178.     Perl:  $foo=`cmd 'safe \$dollar'`;
  179.     
  180.  
  181. 2.3) How come Perl operators have different precedence than C operators?
  182.  
  183.     Actually, they don't; all C operators have the same precedence in Perl as
  184.     they do in C.  The problem is with a class of functions called list
  185.     operators, e.g. print, chdir, exec, system, and so on.  These are somewhat
  186.     bizarre in that they have different precedence depending on whether you
  187.     look on the left or right of them.  Basically, they gobble up all things
  188.     on their right.  For example,
  189.  
  190.     unlink $foo, "bar", @names, "others";
  191.  
  192.     will unlink all those file names.  A common mistake is to write:
  193.  
  194.     unlink "a_file" || die "snafu";
  195.  
  196.     The problem is that this gets interpreted as
  197.  
  198.     unlink("a_file" || die "snafu");
  199.  
  200.     To avoid this problem, you can always make them look like function calls
  201.     or use an extra level of parentheses:
  202.  
  203.     (unlink "a_file") || die "snafu";
  204.     unlink("a_file")  || die "snafu";
  205.  
  206.     Sometimes you actually do care about the return value:
  207.  
  208.     unless ($io_ok = print("some", "list")) { } 
  209.  
  210.     Yes, print() return I/O success.  That means
  211.  
  212.     $io_ok = print(2+4) * 5;
  213.  
  214.     returns 5 times whether printing (2+4) succeeded, and 
  215.     print(2+4) * 5;
  216.     returns the same 5*io_success value and tosses it.
  217.  
  218.     See the Perl man page's section on Precedence for more gory details,
  219.     and be sure to use the -w flag to catch things like this.
  220.  
  221.  
  222. 2.4) How come my converted awk/sed/sh script runs more slowly in Perl?
  223.  
  224.     The natural way to program in those languages may not make for the fastest
  225.     Perl code.  Notably, the awk-to-perl translator produces sub-optimal code;
  226.     see the a2p man page for tweaks you can make.
  227.  
  228.     Two of Perl's strongest points are its associative arrays and its regular
  229.     expressions.  They can dramatically speed up your code when applied
  230.     properly.  Recasting your code to use them can help a lot.
  231.  
  232.     How complex are your regexps?  Deeply nested sub-expressions with {n,m} or
  233.     * operators can take a very long time to compute.  Don't use ()'s unless
  234.     you really need them.  Anchor your string to the front if you can.
  235.  
  236.     Something like this:
  237.     next unless /^.*%.*$/; 
  238.     runs more slowly than the equivalent:
  239.     next unless /%/;
  240.  
  241.     Note that this:
  242.     next if /Mon/;
  243.     next if /Tue/;
  244.     next if /Wed/;
  245.     next if /Thu/;
  246.     next if /Fri/;
  247.     runs faster than this:
  248.     next if /Mon/ || /Tue/ || /Wed/ || /Thu/ || /Fri/;
  249.     which in turn runs faster than this:
  250.     next if /Mon|Tue|Wed|Thu|Fri/;
  251.     which runs *much* faster than:
  252.     next if /(Mon|Tue|Wed|Thu|Fri)/;
  253.  
  254.     There's no need to use /^.*foo.*$/ when /foo/ will do.
  255.  
  256.     Remember that a printf costs more than a simple print.
  257.  
  258.     Don't split() every line if you don't have to.
  259.  
  260.     Another thing to look at is your loops.  Are you iterating through 
  261.     indexed arrays rather than just putting everything into a hashed 
  262.     array?  For example,
  263.  
  264.     @list = ('abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stv');
  265.  
  266.     for $i ($[ .. $#list) {
  267.         if ($pattern eq $list[$i]) { $found++; } 
  268.     } 
  269.  
  270.     First of all, it would be faster to use Perl's foreach mechanism
  271.     instead of using subscripts:
  272.  
  273.     foreach $elt (@list) {
  274.         if ($pattern eq $elt) { $found++; } 
  275.     } 
  276.  
  277.     Better yet, this could be sped up dramatically by placing the whole
  278.     thing in an associative array like this:
  279.  
  280.     %list = ('abc', 1, 'def', 1, 'ghi', 1, 'jkl', 1, 
  281.          'mno', 1, 'pqr', 1, 'stv', 1 );
  282.     $found += $list{$pattern};
  283.     
  284.     (but put the %list assignment outside of your input loop.)
  285.  
  286.     You should also look at variables in regular expressions, which is
  287.     expensive.  If the variable to be interpolated doesn't change over the
  288.     life of the process, use the /o modifier to tell Perl to compile the
  289.     regexp only once, like this:
  290.  
  291.     for $i (1..100) {
  292.         if (/$foo/o) {
  293.         &some_func($i);
  294.         } 
  295.     } 
  296.  
  297.     Finally, if you have a bunch of patterns in a list that you'd like to 
  298.     compare against, instead of doing this:
  299.  
  300.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  301.     foreach $pat (@pats) {
  302.         if ( $name =~ /^$pat$/ ) {
  303.         &some_func();
  304.         last;
  305.         }
  306.     }
  307.  
  308.     If you build your code and then eval it, it will be much faster.
  309.     For example:
  310.  
  311.     @pats = ('_get.*', 'bogus', '_read', '.*exit', '_write');
  312.     $code = <<EOS
  313.         while (<>) { 
  314.             study;
  315. EOS
  316.     foreach $pat (@pats) {
  317.         $code .= <<EOS
  318.         if ( /^$pat\$/ ) {
  319.             &some_func();
  320.             next;
  321.         }
  322. EOS
  323.     }
  324.     $code .= "}\n";
  325.     print $code if $debugging;
  326.     eval $code;
  327.  
  328.  
  329.  
  330. 2.5) How can I call my system's unique C functions from Perl?
  331.  
  332.     If these are system calls and you have the syscall() function, then
  333.     you're probably in luck -- see the next question.  For arbitrary
  334.     library functions, it's not quite so straight-forward.  While you
  335.     can't have a C main and link in Perl routines, if you're
  336.     determined, you can extend Perl by linking in your own C routines.
  337.     See the usub/ subdirectory in the Perl distribution kit for an example
  338.     of doing this to build a Perl that understands curses functions.  It's
  339.     neither particularly easy nor overly-documented, but it is feasible.
  340.  
  341.  
  342. 2.6) Where do I get the include files to do ioctl() or syscall()?
  343.  
  344.     These are generated from your system's C include files using the h2ph
  345.     script (once called makelib) from the Perl source directory.  This will
  346.     make files containing subroutine definitions, like &SYS_getitimer, which
  347.     you can use as arguments to your function.
  348.  
  349.     You might also look at the h2pl subdirectory in the Perl source for how to
  350.     convert these to forms like $SYS_getitimer; there are both advantages and
  351.     disadvantages to this.  Read the notes in that directory for details.  
  352.    
  353.     In both cases, you may well have to fiddle with it to make these work; it
  354.     depends how funny-looking your system's C include files happen to be.
  355.  
  356.     If you're trying to get at C structures, then you should take a look
  357.     at using c2ph, which uses debugger "stab" entries generated by your
  358.     BSD or GNU C compiler to produce machine-independent perl definitions
  359.     for the data structures.  This allows to you avoid hardcoding
  360.     structure layouts, types, padding, or sizes, greatly enhancing
  361.     portability.  c2ph comes with the perl distribution.  On an SCO
  362.     system, GCC only has COFF debugging support by default, so you'll have
  363.     to build GCC 2.1 with DBX_DEBUGGING_INFO defined, and use -gstabs to
  364.     get c2ph to work there.
  365.  
  366.     See the file /pub/perl/info/ch2ph on convex.com via anon ftp 
  367.     for more traps and tips on this process.
  368.  
  369.  
  370. 2.7) Why doesn't "local($foo) = <FILE>;" work right?
  371.  
  372.     Well, it does.  The thing to remember is that local() provides an array
  373.     context, and that the <FILE> syntax in an array context will read all the
  374.     lines in a file.  To work around this, use:
  375.  
  376.     local($foo);
  377.     $foo = <FILE>;
  378.  
  379.     You can use the scalar() operator to cast the expression into a scalar
  380.     context:
  381.  
  382.     local($foo) = scalar(<FILE>);
  383.  
  384.  
  385. 2.8) How can I detect keyboard input without reading it?
  386.  
  387.     You should check out the Frequently Asked Questions list in
  388.     comp.unix.* for things like this: the answer is essentially the same.
  389.     It's very system dependent.  Here's one solution that works on BSD
  390.     systems:
  391.  
  392.     sub key_ready {
  393.         local($rin, $nfd);
  394.         vec($rin, fileno(STDIN), 1) = 1;
  395.         return $nfd = select($rin,undef,undef,0);
  396.     }
  397.  
  398.     A closely related question is how to input a single character from the
  399.     keyboard.  Again, this is a system dependent operation.  The following 
  400.     code that may or may not help you:
  401.  
  402.     $BSD = -f '/vmunix';
  403.     if ($BSD) {
  404.         system "stty cbreak </dev/tty >/dev/tty 2>&1";
  405.     }
  406.     else {
  407.         system "stty", '-icanon',
  408.         system "stty", 'eol', "\001"; 
  409.     }
  410.  
  411.     $key = getc(STDIN);
  412.  
  413.     if ($BSD) {
  414.         system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  415.     }
  416.     else {
  417.         system "stty", 'icanon';
  418.         system "stty", 'eol', '^@'; # ascii null
  419.     }
  420.     print "\n";
  421.  
  422.     You could also handle the stty operations yourself for speed if you're
  423.     going to be doing a lot of them.  This code works to toggle cbreak
  424.     and echo modes on a BSD system:
  425.  
  426.     sub set_cbreak { # &set_cbreak(1) or &set_cbreak(0)
  427.     local($on) = $_[0];
  428.     local($sgttyb,@ary);
  429.     require 'sys/ioctl.ph';
  430.     $sgttyb_t   = 'C4 S' unless $sgttyb_t;  # c2ph: &sgttyb'typedef()
  431.  
  432.     ioctl(STDIN,&TIOCGETP,$sgttyb) || die "Can't ioctl TIOCGETP: $!";
  433.  
  434.     @ary = unpack($sgttyb_t,$sgttyb);
  435.     if ($on) {
  436.         $ary[4] |= &CBREAK;
  437.         $ary[4] &= ~&ECHO;
  438.     } else {
  439.         $ary[4] &= ~&CBREAK;
  440.         $ary[4] |= &ECHO;
  441.     }
  442.     $sgttyb = pack($sgttyb_t,@ary);
  443.  
  444.     ioctl(STDIN,&TIOCSETP,$sgttyb) || die "Can't ioctl TIOCSETP: $!";
  445.     }
  446.  
  447.     Note that this is one of the few times you actually want to use the
  448.     getc() function; it's in general way too expensive to call for normal
  449.     I/O.  Normally, you just use the <FILE> syntax, or perhaps the read()
  450.     or sysread() functions.
  451.  
  452.     For perspectives on more portable solutions, use anon ftp to retrieve
  453.     the file /pub/perl/info/keypress from convex.com.
  454.  
  455.  
  456. 2.9) How can I make an array of arrays or other recursive data types?
  457.  
  458.     Remember that Perl isn't about nested data structures (actually,
  459.     perl0 ..  perl4 weren't, but maybe perl5 will be, at least
  460.     somewhat).  It's about flat ones, so if you're trying to do this, you
  461.     may be going about it the wrong way or using the wrong tools.  You
  462.     might try parallel arrays with common subscripts.
  463.  
  464.     But if you're bound and determined, you can use the multi-dimensional
  465.     array emulation of $a{'x','y','z'}, or you can make an array of names
  466.     of arrays and eval it.
  467.  
  468.     For example, if @name contains a list of names of arrays, you can 
  469.     get at a the j-th element of the i-th array like so:
  470.  
  471.     $ary = $name[$i];
  472.     $val = eval "\$$ary[$j]";
  473.  
  474.     or in one line
  475.  
  476.     $val = eval "\$$name[$i][\$j]";
  477.  
  478.     You could also use the type-globbing syntax to make an array of *name
  479.     values, which will be more efficient than eval.  Here @name hold
  480.     a list of pointers, which we'll have to dereference through a temporary
  481.     variable.
  482.  
  483.     For example:
  484.  
  485.     { local(*ary) = $name[$i]; $val = $ary[$j]; }
  486.  
  487.     In fact, you can use this method to make arbitrarily nested data
  488.     structures.  You really have to want to do this kind of thing
  489.     badly to go this far, however, as it is notationally cumbersome.
  490.  
  491.     Let's assume you just simply *have* to have an array of arrays of
  492.     arrays.  What you do is make an array of pointers to arrays of
  493.     pointers, where pointers are *name values described above.  You
  494.     initialize the outermost array normally, and then you build up your
  495.     pointers from there.  For example:
  496.  
  497.     @w = ( 'ww' .. 'xx' );
  498.     @x = ( 'xx' .. 'yy' );
  499.     @y = ( 'yy' .. 'zz' );
  500.     @z = ( 'zz' .. 'zzz' );
  501.  
  502.     @ww = reverse @w;
  503.     @xx = reverse @x;
  504.     @yy = reverse @y;
  505.     @zz = reverse @z;
  506.  
  507.     Now make a couple of array of pointers to these:
  508.  
  509.     @A = ( *w, *x, *y, *z );
  510.     @B = ( *ww, *xx, *yy, *zz );
  511.  
  512.     And finally make an array of pointers to these arrays:
  513.  
  514.     @AAA = ( *A, *B );
  515.  
  516.     To access an element, such as AAA[i][j][k], you must do this:
  517.  
  518.     local(*foo) = $AAA[$i];
  519.     local(*bar) = $foo[$j];
  520.     $answer = $bar[$k];
  521.  
  522.     Similar manipulations on associative arrays are also feasible.
  523.  
  524.     You could take a look at recurse.pl package posted by Felix Lee
  525.     <flee@cs.psu.edu>, which lets you simulate vectors and tables (lists and
  526.     associative arrays) by using type glob references and some pretty serious
  527.     wizardry.
  528.  
  529.     In C, you're used to creating recursive datatypes for operations
  530.     like recursive decent parsing or tree traversal.  In Perl, these
  531.     algorithms are best implemented using associative arrays.  Take an
  532.     array called %parent, and build up pointers such that $parent{$person}
  533.     is the name of that person's parent.  Make sure you remember that
  534.     $parent{'adam'} is 'adam'. :-) With a little care, this approach can
  535.     be used to implement general graph traversal algorithms as well.
  536.  
  537.  
  538. 2.10) How can I quote a variable to use in a regexp?
  539.  
  540.     From the manual:
  541.  
  542.     $pattern =~ s/(\W)/\\$1/g;
  543.  
  544.     Now you can freely use /$pattern/ without fear of any unexpected
  545.     meta-characters in it throwing off the search.  If you don't know
  546.     whether a pattern is valid or not, enclose it in an eval to avoid
  547.     a fatal run-time error.
  548.  
  549.  
  550. 2.11) Why do setuid Perl scripts complain about kernel problems?
  551.  
  552.     This message:
  553.  
  554.     YOU HAVEN'T DISABLED SET-ID SCRIPTS IN THE KERNEL YET!
  555.     FIX YOUR KERNEL, PUT A C WRAPPER AROUND THIS SCRIPT, OR USE -u AND UNDUMP!
  556.  
  557.     is triggered because setuid scripts are inherently insecure due to a
  558.     kernel bug.  If your system has fixed this bug, you can compile Perl
  559.     so that it knows this.  Otherwise, create a setuid C program that just
  560.     execs Perl with the full name of the script.  
  561.  
  562.  
  563. 2.12) How do I open a pipe both to and from a command?
  564.  
  565.     In general, this is a dangerous move because you can find yourself in a
  566.     deadlock situation.  It's better to put one end of the pipe to a file.
  567.     For example:
  568.  
  569.     # first write some_cmd's input into a_file, then 
  570.     open(CMD, "some_cmd its_args < a_file |");
  571.     while (<CMD>) {
  572.  
  573.     # or else the other way; run the cmd
  574.     open(CMD, "| some_cmd its_args > a_file");
  575.     while ($condition) {
  576.         print CMD "some output\n";
  577.         # other code deleted
  578.     } 
  579.     close CMD || warn "cmd exited $?";
  580.  
  581.     # now read the file
  582.     open(FILE,"a_file");
  583.     while (<FILE>) {
  584.  
  585.     If you have ptys, you could arrange to run the command on a pty and
  586.     avoid the deadlock problem.  See the chat2.pl package in the
  587.     distributed library for ways to do this.
  588.  
  589.     At the risk of deadlock, it is theoretically possible to use a
  590.     fork, two pipe calls, and an exec to manually set up the two-way
  591.     pipe.  (BSD system may use socketpair() in place of the two pipes,
  592.     but this is not as portable.)  The open2 library function distributed
  593.     with the current perl release will do this for you.
  594.  
  595.     It assumes it's going to talk to something like adb, both writing to
  596.     it and reading from it.  This is presumably safe because you "know"
  597.     that commands like adb will read a line at a time and output a line at
  598.     a time.  Programs like sort that read their entire input stream first,
  599.     however, are quite apt to cause deadlock.
  600.  
  601.  
  602. 2.13) How can I change the first N letters of a string?
  603.  
  604.     Remember that the substr() function produces an lvalue, that is, it may be
  605.     assigned to.  Therefore, to change the first character to an S, you could
  606.     do this:
  607.  
  608.     substr($var,0,1) = 'S';
  609.  
  610.     This assumes that $[ is 0;  for a library routine where you can't know $[,
  611.     you should use this instead:
  612.  
  613.     substr($var,$[,1) = 'S';
  614.  
  615.     While it would be slower, you could in this case use a substitute:
  616.  
  617.     $var =~ s/^./S/;
  618.     
  619.     But this won't work if the string is empty or its first character is a
  620.     newline, which "." will never match.  So you could use this instead:
  621.  
  622.     $var =~ s/^[^\0]?/S/;
  623.  
  624.     To do things like translation of the first part of a string, use substr,
  625.     as in:
  626.  
  627.     substr($var, $[, 10) =~ tr/a-z/A-Z/;
  628.  
  629.     If you don't know then length of what to translate, something like
  630.     this works:
  631.  
  632.     /^(\S+)/ && substr($_,$[,length($1)) =~ tr/a-z/A-Z/;
  633.     
  634.     For some things it's convenient to use the /e switch of the 
  635.     substitute operator:
  636.  
  637.     s/^(\S+)/($tmp = $1) =~ tr#a-z#A-Z#, $tmp/e
  638.  
  639.     although in this case, it runs more slowly than does the previous example.
  640.  
  641.  
  642. 2.14) How can I manipulate fixed-record-length files?
  643.  
  644.     The most efficient way is using pack and unpack.  This is faster than
  645.     using substr.  Here is a sample chunk of code to break up and put back
  646.     together again some fixed-format input lines, in this case, from ps.
  647.  
  648.     # sample input line:
  649.     #   15158 p5  T      0:00 perl /mnt/tchrist/scripts/now-what
  650.     $ps_t = 'A6 A4 A7 A5 A*';
  651.     open(PS, "ps|");
  652.     $_ = <PS>; print;
  653.     while (<PS>) {
  654.         ($pid, $tt, $stat, $time, $command) = unpack($ps_t, $_);
  655.         for $var ('pid', 'tt', 'stat', 'time', 'command' ) {
  656.         print "$var: <", eval "\$$var", ">\n";
  657.         }
  658.         print 'line=', pack($ps_t, $pid, $tt, $stat, $time, $command),  "\n";
  659.     }
  660.  
  661.  
  662. 2.15) How can I make a file handle local to a subroutine?
  663.  
  664.     You must use the type-globbing *VAR notation.  Here is some code to
  665.     cat an include file, calling itself recursively on nested local
  666.     include files (i.e. those with #include "file", not #include <file>):
  667.  
  668.     sub cat_include {
  669.         local($name) = @_;
  670.         local(*FILE);
  671.         local($_);
  672.  
  673.         warn "<INCLUDING $name>\n";
  674.         if (!open (FILE, $name)) {
  675.         warn "can't open $name: $!\n";
  676.         return;
  677.         }
  678.         while (<FILE>) {
  679.         if (/^#\s*include "([^"]*)"/) {
  680.             &cat_include($1);
  681.         } else {
  682.             print;
  683.         }
  684.         }
  685.         close FILE;
  686.     }
  687.  
  688.  
  689. 2.16) How can I extract just the unique elements of an array?
  690.  
  691.     There are several possible ways, depending on whether the
  692.     array is ordered and you wish to preserve the ordering.
  693.  
  694.     a) If @in is sorted, and you want @out to be sorted:
  695.  
  696.     $prev = 'nonesuch';
  697.     @out = grep($_ ne $prev && (($prev) = $_), @in);
  698.  
  699.        This is nice in that it doesn't use much extra memory, 
  700.        simulating uniq's behavior of removing only adjacent
  701.        duplicates.
  702.  
  703.     b) If you don't know whether @in is sorted:
  704.  
  705.     undef %saw;
  706.     @out = grep(!$saw{$_}++, @in);
  707.  
  708.     c) Like (b), but @in contains only small integers:
  709.  
  710.     @out = grep(!$saw[$_]++, @in);
  711.  
  712.     d) A way to do (b) without any loops or greps:
  713.  
  714.     undef %saw;
  715.     @saw{@in} = ();
  716.     @out = sort keys %saw;  # remove sort if undesired
  717.  
  718.     e) Like (d), but @in contains only small positive integers:
  719.  
  720.     undef @ary;
  721.     @ary[@in] = @in;
  722.     @out = sort @ary;
  723.  
  724.  
  725. 2.17) How can I call alarm() or usleep() from Perl?
  726.  
  727.     It's available as a built-in as of version 3.038.  If you want finer
  728.     granularity than 1 second (as usleep() provides) and have itimers and
  729.     syscall() on your system, you can use the following.  You could also
  730.     use select().
  731.  
  732.     It takes a floating-point number representing how long to delay until
  733.     you get the SIGALRM, and returns a floating- point number representing
  734.     how much time was left in the old timer, if any.  Note that the C
  735.     function uses integers, but this one doesn't mind fractional numbers.
  736.  
  737.     # alarm; send me a SIGALRM in this many seconds (fractions ok)
  738.     # tom christiansen <tchrist@convex.com>
  739.     sub alarm {
  740.     require 'syscall.ph';
  741.     require 'sys/time.ph';
  742.  
  743.     local($ticks) = @_;
  744.     local($in_timer,$out_timer);
  745.     local($isecs, $iusecs, $secs, $usecs);
  746.  
  747.     local($itimer_t) = 'L4'; # should be &itimer'typedef()
  748.  
  749.     $secs = int($ticks);
  750.     $usecs = ($ticks - $secs) * 1e6;
  751.  
  752.     $out_timer = pack($itimer_t,0,0,0,0);  
  753.     $in_timer  = pack($itimer_t,0,0,$secs,$usecs);
  754.  
  755.     syscall(&SYS_setitimer, &ITIMER_REAL, $in_timer, $out_timer)
  756.         && die "alarm: setitimer syscall failed: $!";
  757.  
  758.     ($isecs, $iusecs, $secs, $usecs) = unpack($itimer_t,$out_timer);
  759.     return $secs + ($usecs/1e6);
  760.     }
  761.  
  762.  
  763. 2.18) How can I test whether an array contains a certain element?
  764.  
  765.     There are several ways to approach this.  If you are going to make
  766.     this query many times and the values are arbitrary strings, the
  767.     fastest way is probably to invert the original array and keep an
  768.     associative array lying about whose keys are the first array's values.
  769.  
  770.     @blues = ('turquoise', 'teal', 'lapis lazuli');
  771.     undef %is_blue;
  772.     for (@blues) { $is_blue{$_} = 1; }
  773.  
  774.     Now you can check whether $is_blue{$some_color}.  It might have been
  775.     a good idea to keep the blues all in an assoc array in the first place.
  776.  
  777.     If the values are all small integers, you could use a simple
  778.     indexed array.  This kind of an array will take up less space:
  779.  
  780.     @primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
  781.     undef @is_tiny_prime;
  782.     for (@primes) { $is_tiny_prime[$_] = 1; }
  783.  
  784.     Now you check whether $is_tiny_prime[$some_number].
  785.  
  786.     If the values in question are integers, but instead of strings,
  787.     you can save quite a lot of space by using bit strings instead:
  788.  
  789.     @articles = ( 1..10, 150..2000, 2017 );
  790.     undef $read;
  791.     grep (vec($read,$_,1) = 1, @articles);
  792.     
  793.     Now check whether vec($read,$n,1) is true for some $n.
  794.  
  795.  
  796. 2.19) How can I do an atexit() or setjmp()/longjmp() in Perl?
  797.  
  798.     Perl's exception-handling mechanism is its eval operator.  You 
  799.     can use eval as setjmp and die as longjmp.  Here's an example
  800.     of Larry's for timed-out input, which in C is often implemented
  801.     using setjmp and longjmp:
  802.  
  803.       $SIG{ALRM} = TIMEOUT;
  804.       sub TIMEOUT { die "restart input\n" }
  805.  
  806.       do { eval { &realcode } } while $@ =~ /^restart input/;
  807.  
  808.       sub realcode {
  809.           alarm 15;
  810.           $ans = <STDIN>;
  811.           alarm 0;
  812.       }
  813.  
  814.    Here's an example of Tom's for doing atexit() handling:
  815.  
  816.     sub atexit { push(@_exit_subs, @_) }
  817.  
  818.     sub _cleanup { unlink $tmp }
  819.  
  820.     &atexit('_cleanup');
  821.  
  822.     eval <<'End_Of_Eval';  $here = __LINE__;
  823.     # as much code here as you want
  824.     End_Of_Eval
  825.  
  826.     $oops = $@;  # save error message
  827.  
  828.     # now call his stuff
  829.     for (@_exit_subs) { &$_() }
  830.  
  831.     $oops && ($oops =~ s/\(eval\) line (\d+)/$0 .
  832.         " line " . ($1+$here)/e, die $oops);
  833.  
  834.     You can register your own routines via the &atexit function now.  You
  835.     might also want to use the &realcode method of Larry's rather than
  836.     embedding all your code in the here-is document.  Make sure to leave
  837.     via die rather than exit, or write your own &exit routine and call
  838.     that instead.   In general, it's better for nested routines to exit
  839.     via die rather than exit for just this reason.
  840.  
  841.     Eval is also quite useful for testing for system dependent features,
  842.     like symlinks, or using a user-input regexp that might otherwise
  843.     blowup on you.
  844.  
  845.  
  846. 2.20) Why doesn't Perl interpret my octal data octally?
  847.  
  848.     Perl only understands octal and hex numbers as such when they occur
  849.     as constants in your program.  If they are read in from somewhere
  850.     and assigned, then no automatic conversion takes place.  You must
  851.     explicitly use oct() or hex() if you want this kind of thing to happen.
  852.     Actually, oct() knows to interpret both hex and octal numbers, while
  853.     hex only converts hexadecimal ones.  For example:
  854.  
  855.     {
  856.         print "What mode would you like? ";
  857.         $mode = <STDIN>;
  858.         $mode = oct($mode);
  859.         unless ($mode) {
  860.         print "You can't really want mode 0!\n";
  861.         redo;
  862.         } 
  863.         chmod $mode, $file;
  864.     } 
  865.  
  866.     Without the octal conversion, a requested mode of 755 would turn 
  867.     into 01363, yielding bizarre file permissions of --wxrw--wt.
  868.  
  869.     If you want something that handles decimal, octal and hex input, 
  870.     you could follow the suggestion in the man page and use:
  871.  
  872.     $val = oct($val) if $val =~ /^0/;
  873.  
  874. 2.21) How do I sort an associative array by value instead of by key?
  875.  
  876.     You have to declare a sort subroutine to do this.  Let's assume
  877.     you want an ASCII sort on the values of the associative array %ary.
  878.     You could do so this way:
  879.  
  880.     foreach $key (sort by_value keys %ary) {
  881.         print $key, '=', $ary{$key}, "\n";
  882.     } 
  883.     sub by_value { $ary{$a} cmp $ary{$b}; }
  884.  
  885.     If you wanted a descending numeric sort, you could do this:
  886.  
  887.     sub by_value { $ary{$b} <=> $ary{$a}; }
  888.  
  889.     You can also inline your sort function, like this:
  890.  
  891.     foreach $key ( sort { $ary{$b} <=> $ary{$a} } keys %ary ) {
  892.         print $key, '=', $ary{$key}, "\n";
  893.     } 
  894.  
  895.     If you wanted a function that didn't have the array name hard-wired
  896.     into it, you could so this:
  897.  
  898.     foreach $key (&sort_by_value(*ary)) {
  899.         print $key, '=', $ary{$key}, "\n";
  900.     } 
  901.     sub sort_by_value {
  902.         local(*x) = @_;
  903.         sub _by_value { $x{$a} cmp $x{$b}; } 
  904.         sort _by_value keys %x;
  905.     } 
  906.  
  907.     If you want neither an alphabetic nor a numeric sort, then you'll 
  908.     have to code in your own logic instead of relying on the built-in
  909.     signed comparison operators "cmp" and "<=>".
  910.  
  911.     Note that if you're sorting on just a part of the value, such as a
  912.     piece you might extract via split, unpack, pattern-matching, or
  913.     substr, then rather than performing that operation inside your sort
  914.     routine on each call to it, it is significantly more efficient to
  915.     build a parallel array of just those portions you're sorting on, sort
  916.     the indices of this parallel array, and then to subscript your original
  917.     array using the newly sorted indices.  This method works on both
  918.     regular and associative arrays, since both @ary[@idx] and @ary{@idx}
  919.     make sense.  See page 245 in the Camel Book on "Sorting an Array by a
  920.     Computable Field" for a simple example of this.
  921.  
  922.  
  923. 2.22) How can I capture STDERR from an external command?
  924.  
  925.     There are three basic ways of running external commands:
  926.  
  927.     system $cmd;
  928.     $output = `$cmd`;
  929.     open (PIPE, "cmd |");
  930.  
  931.     In the first case, both STDOUT and STDERR will go the same place as
  932.     the script's versions of these, unless redirected.  You can always put
  933.     them where you want them and then read them back when the system
  934.     returns.  In the second and third cases, you are reading the STDOUT
  935.     *only* of your command.  If you would like to have merged STDOUT and
  936.     STDERR, you can use shell file-descriptor redirection to dup STDERR to
  937.     STDOUT:
  938.  
  939.     $output = `$cmd 2>&1`;
  940.     open (PIPE, "cmd 2>&1 |");
  941.  
  942.     Another possibility is to run STDERR into a file and read the file 
  943.     later, as in 
  944.  
  945.     $output = `$cmd 2>some_file`;
  946.     open (PIPE, "cmd 2>some_file |");
  947.     
  948.     Here's a way to read from both of them and know which descriptor
  949.     you got each line from.  The trick is to pipe only STDERR through
  950.     sed, which then marks each of its lines, and then sends that
  951.     back into a merged STDOUT/STDERR stream, from which your Perl program
  952.     then reads a line at a time:
  953.  
  954.         open (CMD, 
  955.           "3>&1 (cmd args 2>&1 1>&3 3>&- | sed 's/^/STDERR:/' 3>&-) 3>&- |");
  956.  
  957.         while (<CMD>) {
  958.           if (s/^STDERR://)  {
  959.               print "line from stderr: ", $_;
  960.           } else {
  961.               print "line from stdout: ", $_;
  962.           }
  963.         }
  964.  
  965.     Be apprised that you *must* use Bourne shell redirection syntax
  966.     here, not csh!  In fact, you can't even do these things with csh.
  967.     For details on how lucky you are that perl's system() and backtick
  968.     and pipe opens all use Bourne shell, fetch the file from convex.com
  969.     called /pub/csh.whynot -- and you'll be glad that perl's shell
  970.     interface is the Bourne shell.
  971.  
  972.  
  973. 2.23) Why doesn't open return an error when a pipe open fails?
  974.  
  975.     These statements:
  976.  
  977.     open(TOPIPE, "|bogus_command") || die ...
  978.     open(FROMPIPE, "bogus_command|") || die ...
  979.  
  980.     will not fail just for lack of the bogus_command.  They'll only
  981.     fail if the fork to run them fails, which is seldom the problem.
  982.  
  983.     If you're writing to the TOPIPE, you'll get a SIGPIPE if the child
  984.     exits prematurely or doesn't run.  If you are reading from the
  985.     FROMPIPE, you need to check the close() to see what happened.
  986.  
  987.     If you want an answer sooner than pipe buffering might otherwise
  988.     afford you, you can do something like this:
  989.  
  990.     $kid = open (PIPE, "bogus_command |");   # XXX: check defined($kid)
  991.     (kill 0, $kid) || die "bogus_command failed";
  992.  
  993.     This works fine if bogus_command doesn't have shell metas in it, but
  994.     if it does, the shell may well not have exited before the kill 0.  You
  995.     could always introduce a delay:
  996.  
  997.     $kid = open (PIPE, "bogus_command </dev/null |");
  998.     sleep 1;
  999.     (kill 0, $kid) || die "bogus_command failed";
  1000.  
  1001.     but this is sometimes undesirable, and in any event does not guarantee
  1002.     correct behavior.  But it seems slightly better than nothing.
  1003.  
  1004.     Similar tricks can be played with writable pipes if you don't wish to
  1005.     catch the SIGPIPE.
  1006.  
  1007.  
  1008. 2.24) How can I compare two date strings?
  1009.  
  1010.     If the dates are in an easily parsed, predetermined format, then you
  1011.     can break them up into their component parts and call &timelocal from
  1012.     the distributed perl library.  If the date strings are in arbitrary
  1013.     formats, however, it's probably easier to use the getdate program
  1014.     from the Cnews distribution, since it accepts a wide variety of dates.
  1015.     Note that in either case the return values you will really be
  1016.     comparing will be the total time in seconds as return by time().
  1017.    
  1018.     Here's a getdate function for perl that's not very efficient; you 
  1019.     can do better this by sending it many dates at once or modifying
  1020.     getdate to behave better on a pipe.  Beware the hardcoded pathname.
  1021.  
  1022.     sub getdate {
  1023.         local($_) = shift;
  1024.  
  1025.         s/-(\d{4})$/+$1/ || s/\+(\d{4})$/-$1/; 
  1026.         # getdate has broken timezone sign reversal!
  1027.  
  1028.         $_ = `/usr/local/lib/news/newsbin/getdate '$_'`;
  1029.         chop;
  1030.         $_;
  1031.     } 
  1032.  
  1033.     Richard Ohnemus <rick@IMD.Sterling.COM> actually has a getdate.y
  1034.     for use with the Perl yacc.  You can get this from ftp.sterling.com
  1035.     [192.124.9.1] in /local/perl-byacc1.8.1.tar.Z, or send the author
  1036.     mail for details.
  1037.  
  1038.  
  1039. 2.25) What's the fastest way to code up a given task in perl?
  1040.  
  1041.     Because Perl so lends itself to a variety of different approaches
  1042.     for any given task, a common question is which is the fastest way
  1043.     to code a given task.  Since some approaches can be dramatically
  1044.     more efficient that others, it's sometimes worth knowing which is
  1045.     best.  Unfortunately, the implementation that first comes to mind,
  1046.     perhaps as a direct translation from C or the shell, often yields
  1047.     suboptimal performance.  Not all approaches have the same results
  1048.     across different hardware and software platforms.  Furthermore,
  1049.     legibility must sometimes be sacrificed for speed.
  1050.  
  1051.     While an experienced perl programmer can sometimes eye-ball the code
  1052.     and make an educated guess regarding which way would be fastest,
  1053.     surprises can still occur.  So, in the spirit of perl programming
  1054.     being an empirical science, the best way to find out which of several
  1055.     different methods runs the fastest is simply to code them all up and
  1056.     time them. For example:
  1057.  
  1058.     $COUNT = 10_000; $| = 1;
  1059.  
  1060.     print "method 1: ";
  1061.  
  1062.         ($u, $s) = times;
  1063.         for ($i = 0; $i < $COUNT; $i++) {
  1064.         # code for method 1
  1065.         }
  1066.         ($nu, $ns) = times;
  1067.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1068.  
  1069.     print "method 2: ";
  1070.  
  1071.         ($u, $s) = times;
  1072.         for ($i = 0; $i < $COUNT; $i++) {
  1073.         # code for method 2
  1074.         }
  1075.         ($nu, $ns) = times;
  1076.         printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
  1077.  
  1078.     For more specific tips, see the section on Efficiency in the
  1079.     ``Other Oddments'' chapter at the end of the Camel Book.
  1080.  
  1081.  
  1082. 2.26) How can I know how many entries are in an associative array?
  1083.  
  1084.     While the number of elements in a @foobar array is simply @foobar when
  1085.     used in a scalar, you can't figure out how many elements are in an
  1086.     associative array in an analogous fashion.  That's because %foobar in
  1087.     a scalar context returns the ratio (as a string) of number of buckets
  1088.     filled versus the number allocated.  For example, scalar(%ENV) might
  1089.     return "20/32".  While perl could in theory keep a count, this would
  1090.     break down on associative arrays that have been bound to dbm files.
  1091.  
  1092.     However, while you can't get a count this way, one thing you *can* use
  1093.     it for is to determine whether there are any elements whatsoever in
  1094.     the array, since "if (%table)" is guaranteed to be false if nothing
  1095.     has ever been stored in it.  
  1096.  
  1097.     So you either have to keep your own count around and increments
  1098.     it every time you store a new key in the array, or else do it
  1099.     on the fly when you really care, perhaps like this:
  1100.  
  1101.     $count++ while each %ENV;
  1102.  
  1103.     This preceding method will be faster than extracting the
  1104.     keys into a temporary array to count them.
  1105.  
  1106.     As of a very recent patch, you can say
  1107.  
  1108.     $count = keys %ENV;
  1109.  
  1110.  
  1111.  
  1112. 2.27) Why can't my perl program read from STDIN after I gave it ^D (EOF) ?
  1113.  
  1114.     Because some stdio's set error and eof flags that need clearing.
  1115.  
  1116.     Try keeping around the seekpointer and go there, like this:
  1117.      $where = tell(LOG);
  1118.      seek(LOG, $where, 0);
  1119.  
  1120.     If that doesn't work, try seeking to a different part of the file and
  1121.     then back.  If that doesn't work, try seeking to a different part of
  1122.     the file, reading something, and then seeking back.  If that doesn't
  1123.     work, give up on your stdio package and use sysread.  You can't call
  1124.     stdio's clearerr() from Perl, so if you get EINTR from a signal
  1125.     handler, you're out of luck.  Best to just use sysread() from the
  1126.     start for the tty.
  1127.  
  1128.  
  1129. 2.28) Do I always/never have to quote my strings or use semicolons?
  1130.  
  1131.     You don't have to quote strings that can't mean anything else
  1132.     in the language, like identifiers with any upper-case letters
  1133.     in them.  Therefore, it's fine to do this:
  1134.  
  1135.     $SIG{INT} = Timeout_Routine;
  1136.     or 
  1137.  
  1138.     @Days = (Sun, Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  1139.  
  1140.     but you can't get away with this:
  1141.  
  1142.     $foo{while} = until;
  1143.  
  1144.     in place of 
  1145.  
  1146.     $foo{'while'} = 'until';
  1147.  
  1148.     The requirements on semicolons have been increasingly relaxed.  You no
  1149.     longer need one at the end of a block, but stylistically, you're
  1150.     better to use them if you don't put the curly brace on the same line:
  1151.  
  1152.     for (1..10) { print }
  1153.  
  1154.     is ok, as is
  1155.  
  1156.     @nlist = sort { $a <=> $b } @olist;
  1157.  
  1158.     but you probably shouldn't do this:
  1159.     
  1160.     for ($i = 0; $i < @a; $i++) {
  1161.         print "i is $i\n"  # <-- oops!
  1162.     } 
  1163.  
  1164.     because you might want to add lines later, and anyway, 
  1165.     it looks funny. :-)
  1166.  
  1167.  
  1168. 2.29) How can I translate tildes in a filename?
  1169.  
  1170.     Perl doesn't expand tildes -- the shell (ok, some shells) do.
  1171.     The classic request is to be able to do something like:
  1172.  
  1173.     open(FILE, "~/dir1/file1");
  1174.     open(FILE, "~tchrist/dir1/file1");
  1175.  
  1176.     which doesn't work.  (And you don't know it, because you 
  1177.     did a system call without an "|| die" clause! :-)
  1178.  
  1179.     If you *know* you're on a system with the csh, and you *know*
  1180.     that Larry hasn't internalized file globbing, then you could
  1181.     get away with 
  1182.  
  1183.     $filename = <~tchrist/dir1/file1>;
  1184.  
  1185.     but that's pretty iffy.
  1186.  
  1187.     A better way is to do the translation yourself, as in:
  1188.  
  1189.     $filename =~ s#^~(\w+)(/.*)?$#(getpwnam($1))[7].$2#e;
  1190.  
  1191.     More robust and efficient versions that checked for error conditions,
  1192.     handed simple ~/blah notation, and cached lookups are all reasonable
  1193.     enhancements.
  1194.  
  1195.  
  1196. 2.30) How can I convert my shell script to Perl?
  1197.  
  1198.     Larry's standard answer for this is to send your script to me (Tom
  1199.     Christiansen) with appropriate supplications and offerings.  :-(
  1200.     That's because there's no automatic machine translator.  Even if you
  1201.     were, you wouldn't gain a lot, as most of the external programs would
  1202.     still get called.  It's the same problem as blind translation into C:
  1203.     you're still apt to be bogged down by exec()s.  You have to analyze
  1204.     the dataflow and algorithm and rethink it for optimal speedup.  It's
  1205.     not uncommon to see one, two, or even three orders of magnitude of
  1206.     speed difference between the brute-force and the recoded approaches.
  1207.  
  1208.  
  1209. 2.31) What is variable suicide and how can I prevent it?
  1210.  
  1211.     Variable suicide is a nasty sideeffect of dynamic scoping and
  1212.     the way variables are passed by reference.  If you say
  1213.  
  1214.     $x = 17;
  1215.     &munge($x);
  1216.     sub munge {
  1217.         local($x);
  1218.         local($myvar) = $_[0];
  1219.         ...
  1220.     } 
  1221.  
  1222.     Then you have just clubbered $_[0]!  Why this is occurring 
  1223.     is pretty heavy wizardry: the reference to $x stored in 
  1224.     $_[0] was temporarily occluded by the previous local($x)
  1225.     statement (which, you're recall, occurs at run-time, not
  1226.     compile-time).  The work around is simple, however: declare
  1227.     your formal parameters first:
  1228.  
  1229.     sub munge {
  1230.         local($myvar) = $_[0];
  1231.         local($x);
  1232.         ...
  1233.     }
  1234.  
  1235.     That doesn't help you if you're going to be trying to access
  1236.     @_ directly after the local()s.  In this case, careful use
  1237.     of the package facility is your only recourse.
  1238.  
  1239.     Another manifestation of this problem occurs due to the
  1240.     magical nature of the index variable in a foreach() loop.
  1241.  
  1242.     @num = 0 .. 4;
  1243.     print "num begin  @num\n";
  1244.     foreach $m (@num) { &ug }
  1245.     print "num finish @num\n";
  1246.     sub ug {
  1247.         local($m) = 42;
  1248.         print "m=$m  $num[0],$num[1],$num[2],$num[3]\n";
  1249.     }
  1250.     
  1251.     Which prints out the mysterious:
  1252.  
  1253.     num begin  0 1 2 3 4
  1254.     m=42  42,1,2,3
  1255.     m=42  0,42,2,3
  1256.     m=42  0,1,42,3
  1257.     m=42  0,1,2,42
  1258.     m=42  0,1,2,3
  1259.     num finish 0 1 2 3 4
  1260.  
  1261.     What's happening here is that $m is an alias for each 
  1262.     element of @num.  Inside &ug, you temporarily change
  1263.     $m.  Well, that means that you've also temporarily 
  1264.     changed whatever $m is an alias to!!  The only workaround
  1265.     is to be careful with global variables, using packages,
  1266.     and/or just be aware of this potential in foreach() loops.
  1267.  
  1268.  
  1269. 2.32) Can I use Perl regular expressions to match balanced text?
  1270.  
  1271.     No, or at least, not by the themselves.
  1272.  
  1273.     Regexps just aren't powerful enough.  Although Perl's patterns aren't
  1274.     strictly regular because they do backtracking (the \1 notation), you
  1275.     still can't do it.  You need to employ auxiliary logic.  A simple
  1276.     approach would involve keeping a bit of state around, something 
  1277.     vaguely like this (although we don't handle patterns on the same line):
  1278.  
  1279.     while(<>) {
  1280.         if (/pat1/) {
  1281.         if ($inpat++ > 0) { warn "already saw pat1" } 
  1282.         redo;
  1283.         } 
  1284.         if (/pat2/) {
  1285.         if (--$inpat < 0) { warn "never saw pat1" } 
  1286.         redo;
  1287.         } 
  1288.     }
  1289.  
  1290.     A rather more elaborate subroutine to pull out balanced and possibly
  1291.     nested single chars, like ` and ', { and }, or ( and ) can be found
  1292.     on convex.com in /pub/perl/scripts/pull_quotes.
  1293.  
  1294.  
  1295. 2.33) Can I use Perl to run a telnet or ftp session?
  1296.  
  1297.     Sure, you can connect directly to them using sockets, or you can run a
  1298.     session on a pty.  In either case, Randal's chat2 package, which is
  1299.     distributed with the perl source, will come in handly.  It address
  1300.     much the same problem space as Don Libes's expect package does.  Two
  1301.     examples of using managing an ftp session using chat2 can be found on
  1302.     convex.com in /pub/perl/scripts/ftp-chat2.shar .
  1303.  
  1304.     Caveat lector: chat2 is documented only by example, may not run on
  1305.     System V systems, and is subtly machine dependent both in its ideas
  1306.     of networking and in pseudottys.
  1307.  
  1308.  
  1309. 2.34) What does "Malformed command links" mean?
  1310.  
  1311.     This is a bug in 4.035.  While in general it's merely a cosmetic
  1312.     problem, it often comanifests with a highly undesirable coredumping
  1313.     problem.  Programs known to be affected by the fatal coredump include
  1314.     plum and pcops.  Since perl5 is pretty much a total rewrite, we can
  1315.     count on it being fixed then, but if anyone tracks down the coredump
  1316.     problem before then, a significant portion of the Perl world would
  1317.     rejoice.
  1318.  
  1319.  
  1320. 2.35) How can I set up a footer format to be used with write()?
  1321.  
  1322.     While the $^ variable contains the name of the current header format,
  1323.     there is no corresponding mechanism to automatically do the same thing
  1324.     for a footer.  Not knowing how big a format is going to be until you
  1325.     evaluate it is one of the major problems.
  1326.  
  1327.     If you have a fixed-size footer, you can get footers by checking for
  1328.     line left on page ($-) before each write, and printing the footer
  1329.     yourself if necessary.
  1330.  
  1331.     Another strategy is to open a pipe to yourself, using open(KID, "|-")
  1332.     and always write()ing to the KID, who then postprocesses its STDIN to
  1333.     rearrange headers and footers however you like.  Not very convenient,
  1334.     but doable.
  1335.  
  1336.  
  1337. 2.36) Why does my Perl program keep growing in size?
  1338.  
  1339.     While there may be a real memory leak in the Perl source code or even
  1340.     whichever malloc() you're using, common causes are incomplete eval()s
  1341.     or local()s in loops.
  1342.  
  1343.     An eval() which terminates in error due to a failed parsing 
  1344.     will leave a bit of memory unusable.
  1345.  
  1346.     A local() inside a loop:
  1347.  
  1348.     for (1..100) {
  1349.         local(@array);
  1350.     } 
  1351.  
  1352.     will build up 100 versions of @array before the loop is done.
  1353.     The work-around is:
  1354.  
  1355.     local(@array);
  1356.     for (1..100) {
  1357.         undef @array;
  1358.     } 
  1359.  
  1360.     Larry reports that this behavior is fixed for perl5.
  1361.  
  1362. print "Just another Perl hacker,"
  1363. -- 
  1364. Randal L. Schwartz / Stonehenge Consulting Services (503)777-0095
  1365. merlyn@ora.com (semi-permanent) merlyn@kandinsky.intel.com (NEWSREADING ONLY)
  1366. Quote: "Welcome to Portland, Oregon, home of the California Raisins!"
  1367. e California Raisins!"
  1368.